<template>
  <div>
    <a-spin :spinning="treeLoading">
      <a-input-search v-model="searchValue" style="margin-bottom: 8px" placeholder="请输入搜索内容" @change="onChange" />
      <a-tree
        @expand="onExpand"
        @select="onSelect"
        :loading="true"
        :expandedKeys="expandedKeys"
        :defaultSelectedKeys="[defaultdKeys]"
        :autoExpandParent="autoExpandParent"
        :treeData="treeData"
        :class="{ activeEllipsis: isShowEllipsis }"
      >
        <template slot="title" slot-scope="{ title }" class="item">
          <a-tooltip placement="topLeft" :title="title">
            <span v-if="title.indexOf(searchValue) > -1">
              {{ title.substr(0, title.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
            </span>
            <span v-else>{{ title }}</span>
          </a-tooltip>
        </template>
      </a-tree>
    </a-spin>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "SearchTree",
  props: {
    data: {
      type: Array,
      require: true
    },
    defaultdKeys: {
      type: String,
      require: false
    },
    isShowEllipsis: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      searchValue: "",
      expandedKeys: ["0"],
      autoExpandParent: true,
      dataList: [],
      treeData: [],
      keys: "",
      selectedKeys: [],
      selectedTitles: []
    };
  },
  computed: {
    treeLoading() {
      return this.treeData !== null && this.treeData.length <= 0;
    }
  },
  watch: {
    data: {
      handler(val, oldVal) {
        this.dataList = [];
        if (val !== null) {
          this.generateList(val);
          this.treeData = val;
          if (this.treeData.length > 0) {
            this.keys = this.treeData[0].children[0].title; //找到第二级下面第一个，树形展开
          }
          // this.search1(this.keys);
          this.search(this.keys);
        }
      },
      immediate: true
    }
  },

  methods: {
    getSelectedKey() {
      return this.selectedKeys[0] || "";
    },
    getSelectedKeys() {
      return this.selectedKeys;
    },
    getSelectedTitle() {
      return this.selectedTitles[0] || "";
    },
    getSelectedTitles() {
      return this.selectedTitles;
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys;
      if (this.selectedKeys.length > 0) {
        this.selectedTitles = info.selectedNodes.map(
          i => i.data.props.dataRef.title
        );
        this.keys = this.selectedTitles;
        this.$emit(
          "selected",
          this.selectedKeys,
          this.selectedTitles,
          info.selectedNodes[0].data.props.dataRef
        );
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        if (node.scopedSlots === undefined) {
          node.scopedSlots = { title: "title" };
        }
        this.dataList.push({ key: node.key, title: node.title });
        if (node.children) {
          this.generateList(node.children);
        }
      }
    },
    getParentKey(key, tree) {
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.title === key)) {
            parentKey = node.key;
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    onChange(e) {
      const value = e.target.value;
      this.search(value);
      // this.search1(value)
    },
    search1(val) {
      // console.time("test");
      let arr = [...this.treeData];
      let bfs = [];
      if (val != "") {
        while (arr.length) {
          if (arr[0].title.indexOf(val) > -1) {
            bfs.push(arr[0].value);
          }
          arr[0].children.length > 0 && arr.push(...arr[0].children);
          arr.shift();
        }

        Object.assign(this, {
          expandedKeys: bfs,
          // searchValue: val,
          autoExpandParent: true,
          keys: val
        });
        // console.timeEnd("test");
      }
    },
    search(value) {
      // console.time("test");

      const expandedKeys =
        value === ""
          ? ["0"]
          : this.dataList
              .map(item => {
                if (item.title.indexOf(value) > -1) {
                  return this.getParentKey(item.title, this.treeData);
                }
                return null;
              })
              .filter((item, i, self) => item && self.indexOf(item) === i);

      // console.timeEnd("test");
      // console.log(expandedKeys);

      Object.assign(this, {
        expandedKeys,
        // searchValue: value,
        autoExpandParent: true,
        keys: value
      });
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .activeEllipsis .ant-tree-node-content-wrapper {
  width: 130px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
